<?php
namespace app\common;

use app\system\model\SystemToken;
use app\system\model\User;
use think\Controller;

class Base extends Controller {

    protected $sign;               // 签名信息
    protected $requestData;        // 请求参数
    protected $userInfo;           // 当前登录用户信息
    protected $module;             // 当前操作模块
    protected $controller;         // 当前操作控制器
    protected $action;             // 当前操作方法

    /**
     * 基础
     * @author wws
     * @date 2020/11/13 17:14
     */
    public function _initialize() {

        $this->module = $this->request->module();
        $this->controller = $this->request->controller();
        $this->action = $this->request->action();
        $post = $this->request->post();
        $get = $this->request->get();
        $request = empty($get)&& empty($post)?$this->request->instance()->request() : [];
        $this->requestData = array_merge($get,$post,$request);

        // 验证签名
        $this->checkoutSign();


        // 验证用户信息
        $this->checkoutUser();
    }

    /**
     * 验证签名
     * @author wws
     * @date 2020/11/13 17:16
     */
    private function checkoutSign() {
        $checkoutSignResult = false;

        // 开启签名验证前提下
        $signConfig = config('sign');
        if($signConfig['sign_open']) {
            $request = $_REQUEST;
            // 去掉s的参数 Linux会加s 做路由处理
            unset($request['s']);
            if (!empty($request['sign'])) {
                // 排序
                ksort($request);
                $params = '';
                foreach ($request as $key => $value) {
                    // 跳过sign不加验
                    if ($key == 'sign' || $key == 'token') {
                        continue;
                    }
                    $params .= $key . "=" . $value . "&";
                }

                $params = $params . 'key=' . $signConfig['key'];
                $sign = md5($params);
                $this->sign = $sign;
                if ($request['sign'] == $sign) {
                    $checkoutSignResult = true;
                }else{
                    // 开启不验证签名开关
                    if($signConfig['debug']){
                        $checkoutSignResult = true;
                    }
                }
            }
        }else {
            $checkoutSignResult = true;
        }

        if(!$checkoutSignResult){
            $showSign = '';
            // 开启签名展示
            if(config('sign.show_sign')) {
                $showSign = $this->sign;
            }

            errorJson('签名错误 '. $showSign);
        }
    }

    /**
     * 验证用户信息
     * @author wws
     * @date 2020/11/13 17:16
     */
    private function checkoutUser() {
        $isAllowUnLogin = $this->isAllowUnLogin();

        if(!$isAllowUnLogin) {
            // 不可未登录就访问， 验证用户token信息
            $userId = $this->checkoutToken();
            if($userId <= 0) {
                errorJson('无效token');
            }

            // 获取用户信息
            $this->setUserInfo($userId);
        }
    }

    /**
     * 验证是否可未登录直接访问
     * @author wws
     * @date 2020/11/13 17:16
     */
    private function isAllowUnLogin() {
        $isAllowUnLogin = false;

        $allow = [
            'system' => ['login', ],
        ];

        foreach($allow as $module => $value) {
            if($this->module == $module && in_array($this->controller, $value)) {
                $isAllowUnLogin = true;
            }
        }

        return $isAllowUnLogin;

    }

    /**
     * 验证用户token信息
     * @author wws
     * @date 2020/11/13 17:16
     */
    private function checkoutToken() {
        $systemTokenModel = new SystemToken();
        $userId = 0;

        $header = $this->request->header();
        $token = isset($header['token']) ? $header['token'] : '';
        if(empty($token)) return $userId;

        // 检查token
        $condition['token'] = $token;
        $condition['login_time'] = ['<',time() - config('token.expired_time')];
        $tokenInfo = $systemTokenModel->getBaseQuery(['where' => $condition]);
        $userId = !empty($tokenInfo['user_id']) ? $tokenInfo['user_id'] : 0;

        return intval($userId);
    }

    /**
     * 获取并设置用户信息
     * @author wws
     * @date 2020/11/13 17:16
     */
    private function setUserInfo($userId) {
        $userModel = new User();

        $query = [
            'alias' => 'user',
            'where' => [
                'user.user_id' => $userId,
                'user.is_del' => 0,
                'user.is_disabled' => 0,
            ],
            'field' => [
                'user.user_id', 'user.real_name', 'user.company_id', 'user.role_id',
                'company.company_name', 'role.role_name',
            ],
            'join'      => [
                [
                    'erp_system_company company',
                    'company.company_id = user.company_id',
                    'LEFT'
                ],
                [
                    'erp_system_role role',
                    'role.role_id = user.role_id',
                    'LEFT'
                ],
            ],
        ];
        $userInfo = $userModel->getBaseQuery($query);

        $this->userInfo = &$userInfo;
    }
}
